package only.level5.railgun.ysartifactsimulation.task;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import only.level5.railgun.ysartifactsimulation.Bean.CalcData;
import only.level5.railgun.ysartifactsimulation.publisher.HutaoDmgPublisher;
import only.level5.railgun.ysartifactsimulation.utils.ArtifactUtils;
import only.level5.railgun.ysartifactsimulation.utils.CalcUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;

import static only.level5.railgun.ysartifactsimulation.utils.ArtifactUtils.removeRubbish;

@Component
public class FarmTask {

    AtomicInteger time = new AtomicInteger(0);

    // 双黄0.067737
    @Scheduled(fixedRate = 1000)
    public void farmArtifact() throws JsonProcessingException {
        long t0 = System.currentTimeMillis();

        ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();

        boolean isDouble = threadLocalRandom.nextFloat() < 0.067737;
        int farmTime = this.time.incrementAndGet();
        double[] artifact = ArtifactUtils.singleArtifact(farmTime);
        CalcData calcData = CalcUtils.incrementCalc(artifact);
        if (isDouble) {
            artifact = ArtifactUtils.singleArtifact(farmTime);
            calcData = CalcUtils.incrementCalc(artifact);
        }
        if(calcData != null){
            calcData.setTimes(farmTime);
            removeRubbish();
            long t1 = System.currentTimeMillis();
            System.out.println((t1 - t0)/1000);
            publishDmg(calcData);
        }

    }

    private static final ObjectMapper mapper = new ObjectMapper();

    @Autowired
    HutaoDmgPublisher hutaoDmgPublisher;
    public void publishDmg(CalcData calcData) throws JsonProcessingException {
        String message = mapper.writeValueAsString(calcData);
        hutaoDmgPublisher.sendData(message);
    }


}
